/**
 * This file is part of 1genia trampoline
 * Copyright (C) 2007 1genia (contact@1genia.com)
 *
 * This library is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; version 3 of the License. 
 *
 * This library is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Library General Public License for more details. 
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; see the file COPYING.TXT.  If not,
 * write to the Free Software Foundation, Inc., 51 Franklin Street,
 * Fifth Floor, Boston, MA 02110-1301, USA. 
 **/
package com.genia.toolbox.persistence.memory.criteria.criterion;

import com.genia.toolbox.persistence.basis.criteria.BasicCriteriaResult;
import com.genia.toolbox.persistence.basis.manager.AbstractPersistenceManager;
import com.genia.toolbox.persistence.exception.AggregateException;
import com.genia.toolbox.persistence.exception.FieldDefinitionException;
import com.genia.toolbox.persistence.memory.criteria.MemoryCriteria;
import com.genia.toolbox.persistence.memory.criteria.field.AbstractMemoryField;

/**
 * This criterion represent an comparaison between two fields.
 */
public class MemoryFieldComparator
    implements MemoryCriterion
{

  /**
   * this enum represents all the available comparaisons.
   */
  public enum FieldComparator
  {

    /**
     * this represent the equality between two fields.
     */
    EQUALITY
    {
      /**
       * this method compare the two values.
       * 
       * @param value1
       *          the first operand
       * @param value2
       *          the second operand
       * @return <code>true</code> if the values match the comparaison
       */
      @Override
      public boolean match(final Object value1, final Object value2)
      {
        return super.match(value1, value2, new Matcher()
        {
          public boolean match(final double value)
          {
            return value == 0;
          }



          public boolean handleNull(final Object value1, final Object value2)
          {
            return false;
          }
        });
      }

    },
    /**
     * this represents that a numeric field is greater of equals to another.
     */
    GREATER_OR_EQUALS
    {
      /**
       * this method compare the two values.
       * 
       * @param value1
       *          the first operand
       * @param value2
       *          the second operand
       * @return <code>true</code> if the values match the comparaison
       */
      @Override
      public boolean match(final Object value1, final Object value2)
      {
        return super.match(value1, value2, new Matcher()
        {
          public boolean match(final double value)
          {
            return value >= 0;
          }



          public boolean handleNull(final Object value1, final Object value2)
          {
            return false;
          }
        });
      }
    },
    /**
     * this represents that a numeric field is greater than another.
     */
    GREATER_THAN
    {
      /**
       * this method compare the two values.
       * 
       * @param value1
       *          the first operand
       * @param value2
       *          the second operand
       * @return <code>true</code> if the values match the comparaison
       */
      @Override
      public boolean match(final Object value1, final Object value2)
      {
        return super.match(value1, value2, new Matcher()
        {
          public boolean match(final double value)
          {
            return value > 0;
          }



          public boolean handleNull(final Object value1, final Object value2)
          {
            return false;
          }
        });
      }
    };

    /**
     * this interface allow to decide which find of match is correct from a
     * comparaison.
     */
    private interface Matcher
    {
      /**
       * From the result of a comparaison, decide wether we accept the elements
       * or not.
       * 
       * @param value
       *          the result of the comparaison
       * @return <code>true</code> is we accept the elements
       */
      public boolean match(double value);



      /**
       * Determine what to do if either value is null.
       * 
       * @param value1
       *          the first operand
       * @param value2
       *          the second operand
       * @return <code>true</code> is we accept the elements
       */
      public boolean handleNull(Object value1, Object value2);
    }



    /**
     * this method compare the two values.
     * 
     * @param value1
     *          the first operand
     * @param value2
     *          the second operand
     * @return <code>true</code> if the values match the comparaison
     */
    public abstract boolean match(Object value1, Object value2);



    /**
     * this method compare two values and decide with the <code>Matcher</code>
     * if the result is correct.
     * 
     * @param value1
     *          the first operand
     * @param value2
     *          the second operand
     * @param matcher
     *          the <code>Matcher</code> for deciding if the result is correct
     * @return <code>true</code> if the values match the comparaison
     */
    @SuppressWarnings("unchecked")
    private boolean match(final Object value1, final Object value2, final Matcher matcher)
    {
      if (value1 == null || value2 == null) {
        return matcher.handleNull(value1, value2);
      }
      if (value1.equals(value2)) {
        return matcher.match(0);
      }
      if (value1 instanceof Number && value2 instanceof Number) {
        return matcher.match((((Number) value1).doubleValue() - ((Number) value2).doubleValue()));
      }
      if (value1 instanceof Comparable) {
        try {
          return matcher.match(((Comparable) value1).compareTo(value2));
        }
        catch (final Exception e) { // NOPMD
          // Do Nothing.
        }
      }
      return matcher.match(value1.toString().compareTo(value2.toString()));

    }
  }

  /**
   * the comparator for this field.
   */
  private final transient FieldComparator fieldComparator;

  /**
   * the first operand.
   */
  private final transient AbstractMemoryField field1;

  /**
   * the second operand.
   */
  private final transient AbstractMemoryField field2;



  /**
   * constructor.
   * 
   * @param fieldComparator
   *          the comparator for this field
   * @param field1
   *          the first operand
   * @param field2
   *          the second operand
   */
  public MemoryFieldComparator(final FieldComparator fieldComparator, final AbstractMemoryField field1, final AbstractMemoryField field2)
  {
    this.fieldComparator = fieldComparator;
    this.field1 = field1;
    this.field2 = field2;
  }



  /**
   * return <code>true</code> if the <code>BasicCriteriaResult</code> given
   * in parameter match this <code>Criterion</code> in the
   * <code>Criteria> criteria</code>.
   * 
   * @param persistenceManager
   *          the implementation of <code>PersistenceManager</code>
   * @param criteria
   *          the criteria this <code>Criterion</code> comes from
   * @param line
   *          the line to test
   * @return if the <code>BasicCriteriaResult</code> given in parameter match
   *         this <code>Criterion</code>.
   * @throws FieldDefinitionException
   *           when there is an error in the definition of the field
   * @throws AggregateException
   *           when there is an error with an aggregate definition
   */
  public boolean match(final AbstractPersistenceManager persistenceManager, final MemoryCriteria<?> criteria, final BasicCriteriaResult<?> line)
      throws FieldDefinitionException, AggregateException
  {
    return fieldComparator.match(field1.getSimpleValue(line), field2.getSimpleValue(line));
  }



  /**
   * Creates and returns a deep copy of this object.
   * 
   * @return a deep copy of this object
   */
  @Override
  public MemoryFieldComparator clone()
  {
    return this;
  }

}
